package com.wx.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.wx.service.FileUploadService;
import com.wx.utils.BASE64DecodedMultipartFile;


@Service("FileUploadService")
public class FileUploadServiceImpl implements FileUploadService {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);
	
	@Override
	public Map<String, Object> upload(MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> map = new HashMap<String,Object>();
		 if(file.isEmpty()){
		 }
		 String fileName = file.getOriginalFilename();
        String type = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        String fName = new Date().getTime()+"."+type;  
        String pathFlag = getFileType(fileName);
        String saveDir = "/asset/upload/"+pathFlag;
        String path = getRootPath()+saveDir;
        File targetFile = new File(path, fName);  
	        if(!targetFile.exists()){  
	            targetFile.mkdirs();  
	        }  
       //保存  
       try {
           file.transferTo(targetFile);  
           map.put("size", file.getSize());
           map.put("status", true);
       	   map.put("msg", "上传成功");
       } catch (Exception e) { 
           e.printStackTrace();
           logger.error("wrong for FileUploadServiceImpl.class of method upload to upload file",e);
       }  
       String urlpath = request.getContextPath();
       String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+urlpath;
       map.put("name", fName);
       map.put("path", saveDir+"/"+fName);//保存
		map.put("viewPath", /* Configure.getUrl()+ */saveDir+"/"+fName);//显示
	   return map;
	}

	@Override
	public Map<String, Object> Base64ToImage(String data, String logoState,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> map = new HashMap<String,Object>();
		if (data == null) {
			return null;
		}
		data = data.replace("data:image/jpg;base64,", "");
		data = data.replace("data:image/png;base64,", "");
		data = data.replace("data:image/jpeg;base64,", "");
		try {
			// Base64解码
			byte[] b = Base64.getDecoder().decode(data);
	        //img = new String(Base64.getEncoder().encode(picdata));
			// System.out.println("解码完成");
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			String fName = new Date().getTime() + ".png";
			String saveDir = "/asset/upload/pic/" + fName;
			String path = getRootPath() + saveDir;
			File targetFile = new File(getRootPath()+"/asset/upload/pic/");
	        if(!targetFile.isDirectory()){  
	            targetFile.mkdirs();  
	        } 
			OutputStream out = new FileOutputStream(path);
			out.write(b);
			out.flush();
			out.close();
			String urlpath = request.getContextPath();
	       String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+urlpath;
		   map.put("code", "1");
		   map.put("msg", "上传成功");
	       map.put("name", fName);
	       map.put("path", saveDir);//保存
			map.put("viewPath", /* Configure.getUrl()+ */saveDir);//显示
		   return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "-1");
			   map.put("msg", "上失败");
		       map.put("name", "");
		       map.put("path", "");//保存
		       map.put("viewPath", "");//显示
			return map;
		}
	}
	
	/**
	 * 
	 * @Description: <p>区分文件类型</p>
	 * @author ChenJiaLu
	 * @date 2016-10-18
	 * @param @param filename
	 * @param @return   
	 * @return String
	 */
	private static String getFileType(String filename) {
		logger.info("into to FileUploadServiceImpl.class of method getFileType to get file type");
		try{
		filename = filename.toLowerCase();
		if (filename.indexOf("jpg") != -1 || filename.indexOf("bmp") != -1 
				|| filename.indexOf("png") != -1 || filename.indexOf("gif") != -1
				|| filename.indexOf("jpeg") != -1) {
			
			return "pic";
		}
		if (filename.indexOf("tar") != -1 || filename.indexOf("rar") != -1
				|| filename.indexOf("apk") != -1 || filename.indexOf("zip") != -1
				|| filename.indexOf("bin") != -1) {
			return "file";
		}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("wrong for FileUploadServiceImpl.class of method getFileType to get file type",e);
		}
		return "up";
	}
	/**
	 * 
	 * @Description: <p>保存文件，获取物理路径</p>
	 * @author ChenJiaLu
	 * @date 2016-10-18
	 * @param @return   
	 * @return String
	 */
	public  static String getRootPath() {
		logger.info("into to FileUploadServiceImpl.class of method getRootPath to get upload file root path");
		String result = FileUploadServiceImpl.class.getResource("/").toString();
		int index = result.indexOf("WEB-INF");
		if (index == -1) {
			index = result.indexOf("bin");
		}
		result = result.substring(0, index);
		if (result.startsWith("jar"))
			result = result.substring(9); // 当class文件在jar文件中时，返回"jar:file:/F:/ ..."样的路径

		else if (result.startsWith("file"))
			result = result.substring(5); // 当class文件在class文件中时，返回"file:/F:/ ..."样的路径
		try {
			result = URLDecoder.decode(result, "utf-8");// 解决空格问题
		} catch (Exception e) {
			logger.error("wrong for FileUploadServiceImpl.class of method getRootPath to get upload file root path",e);
			return result;
		}
		return result;

	}

	public static MultipartFile base64ToMultipart(String base64) {
		String[] baseStrs = base64.split(",");

        //BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        //b = decoder.decodeBuffer(baseStrs[1]);
        Base64.getDecoder().decode(baseStrs[1]);
        
        for(int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        return new BASE64DecodedMultipartFile(b, baseStrs[0]);
	}
	
}
